package com.chebaohui.iqs.service.impl.deal.util;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import org.apache.http.Consts;
import org.apache.http.message.BasicNameValuePair;
import javax.net.ssl.SSLContext;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

/**
 * 工具类---HttpClient访问
 * 
 * @author xielonghai
 *
 */
public class HttpClient {
	/**
	 * GET请求
	 * 
	 * @param httpClient
	 * @param httpContext
	 * @param url
	 *            路径
	 * @return
	 * @throws Exception
	 */
	public static String _httpGetToBody(CloseableHttpClient httpClient, HttpClientContext httpContext, String url)
			throws Exception {

		CloseableHttpResponse response = _httpGetToResponse(httpClient, httpContext, url);

		try {
			return EntityUtils.toString(response.getEntity());
		} finally {
			response.getEntity().getContent().close();
			// response.close();
		}
	}

	/**
	 * POST请求
	 * 
	 * @param httpClient
	 * @param httpContext
	 * @param url
	 *            路径
	 * @param params
	 *            请求参数
	 * @return
	 * @throws Exception
	 */
	public static String _httpPostToBody(CloseableHttpClient httpClient, HttpClientContext httpContext, String url,
			ArrayList<BasicNameValuePair> params) throws Exception {

		CloseableHttpResponse response = _httpPostToResponse(httpClient, httpContext, url, params);

		try {
			return EntityUtils.toString(response.getEntity());
		} finally {
			response.getEntity().getContent().close();
			// response.close();
		}
	}

	/**
	 * POST请求----JSON
	 * 
	 * @param httpClient
	 * @param httpContext
	 * @param url
	 *            路径
	 * @param jsonParams
	 *            请求参数(JSON)
	 * @return
	 * @throws Exception
	 */
	public static String _httpPostToBody_json(CloseableHttpClient httpClient, HttpClientContext httpContext, String url,
			String jsonParams) throws Exception {

		CloseableHttpResponse response = _httpPostToResponse_json(httpClient, httpContext, url, jsonParams);

		try {
			return EntityUtils.toString(response.getEntity());
		} finally {
			response.getEntity().getContent().close();
			// response.close();
		}
	}

	/**
	 * GET请求
	 */
	private static CloseableHttpResponse _httpGetToResponse(CloseableHttpClient httpClient,
			HttpClientContext httpContext, String url) throws Exception {

		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestconfing = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
				.build();
		httpGet.setConfig(requestconfing);
		CloseableHttpResponse response = httpClient.execute(httpGet, httpContext);
		return response;

	}

	/**
	 * POST请求
	 */
	private static CloseableHttpResponse _httpPostToResponse(CloseableHttpClient httpClient,
			HttpClientContext httpContext, String url, ArrayList<BasicNameValuePair> params) throws Exception {

		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestconfing = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
				.build();
		httpPost.setConfig(requestconfing);
		if (params != null) {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
			httpPost.setEntity(entity);
		}
		CloseableHttpResponse response = httpClient.execute(httpPost, httpContext);

		return response;

	}

	/**
	 * POST请求--JOSN
	 */
	private static CloseableHttpResponse _httpPostToResponse_json(CloseableHttpClient httpClient,
			HttpClientContext httpContext, String url, String jsonParams) throws Exception {
		StringEntity entity = new StringEntity(jsonParams, "UTF-8");

		entity.setContentEncoding("UTF-8");

		entity.setContentType("application/json");

		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestconfing = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
				.build();
		httpPost.setConfig(requestconfing);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = httpClient.execute(httpPost, httpContext);

		return response;

	}

	/**
	 * https 必须用此方法创建httpclient实例(需要证书文件，适合通用HTTPS)
	 * 
	 * @return CloseableHttpClient实体
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				@SuppressWarnings("unused")
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}

				@Override
				public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
						throws java.security.cert.CertificateException {
					return true;
				}
			}).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);

			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
}
